package com.luocc.ccdemo.interceptor

import android.content.Context
import android.util.Log
import okhttp3.Interceptor
import okhttp3.Response

class SaveCookieInterceptor(private val context: Context) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        if (request.url.toString() == "https://www.wanandroid.com/user/logout/json") {
            clearCookie()
        } else {
            val cookies = response.headers("Set-Cookie")
            if (cookies.isNotEmpty()) {
                val cookie = parseCookie(cookies)
                saveCookie(request.url.host, cookie)
            }
        }
        return response
    }

    private fun parseCookie(cookies: List<String>): String {
        val builder = StringBuilder()
        val set = HashSet<String>()
        cookies.forEach {
            val split = it.split(";")
            set.addAll(split)
        }
        set.forEach {
            builder.append(it).append(";")
        }
        val lastIndexOf = builder.lastIndexOf(";")
        return builder.deleteAt(lastIndexOf).toString()
    }

    private fun saveCookie(host: String, cookie: String) {
        val sp = context.getSharedPreferences("user", Context.MODE_PRIVATE)
        val edit = sp.edit()
        edit.putString(host, cookie)
        edit.apply()
    }

    private fun clearCookie() {
        Log.d("LC_", "clearCookie")
        val sharedPreferences = context.getSharedPreferences("user", Context.MODE_PRIVATE)
        val edit = sharedPreferences.edit()
        edit.clear()
        edit.apply()
    }
}